package com.syher.quartz.task.service.impl;

import com.syher.quartz.common.ConstantValue;
import com.syher.quartz.core.config.quartz.exception.ScheduleException;
import com.syher.quartz.core.config.quartz.scheduled.ScheduledManager;
import com.syher.quartz.task.job.TaskJob;
import com.syher.quartz.task.model.TaskInfo;
import com.syher.quartz.task.service.ITaskService;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Map;

/**
 * Created by shenyuhang on 2018/3/7.
 */
@Service
public class TaskService implements ITaskService {

    @Autowired
    Scheduler scheduler;

    ScheduledManager manager;

    @PostConstruct
    public void instance() {
        manager = ScheduledManager.builder();
        manager.setScheduler(scheduler).setRepeat(false);
    }

    @Override
    public void add(TaskInfo taskInfo, Map<String, Object> params) {
        try {
            manager.setJobDetail(taskInfo.getName(), taskInfo.getGroup(), TaskJob.class);
            manager.putDataMap(ConstantValue.DEFAULT_TASK_JOB, taskInfo);
            if (params != null && !params.isEmpty()) {
                params.forEach((k, v) -> {
                    manager.putDataMap(k, v);
                });
            }
            manager.add(taskInfo.getName(), taskInfo.getGroup(), taskInfo.getStart(), taskInfo.getEnd(), taskInfo.getInterval());
        } catch (SchedulerException e) {
            throw new ScheduleException(String.format("Error to add Scheduled Task[%s].", taskInfo.getName()));
        }

    }

    @Override
    public void delete(TaskInfo taskInfo) {
        try {
            manager.delete(taskInfo.getName(), taskInfo.getGroup());
        } catch (SchedulerException e) {
            throw new ScheduleException(String.format("Error to delete Scheduled Task[%s].", taskInfo.getName()));
        }
    }
}
